//
//  UTAddTaskCounterViewController.swift
//  UniversalTool
//
//  Created by LGB on 2025/3/7.
//

import UIKit

class UTAddTaskCounterViewController: UTBaseViewController {
    
    var reloadData:(() -> Void)?

    @IBOutlet weak var taskName: UITextField!
    @IBOutlet weak var number: UITextField!
    @IBOutlet weak var note: UITextField!
    @IBOutlet weak var noButton: UIButton!
    @IBOutlet weak var yesButton: UIButton!
    
    lazy var model: UTTaskCounterItemModel = {
        let model = UTTaskCounterItemModel()
        return model
    }()
    
    lazy var data: UTTaskCounterModel = {
        if let data = UTTaskCounterHelper.taskCounterInfo() {
            return data
        }
        return UTTaskCounterModel()
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .clear
    }
    
    @IBAction func didClose(_ sender: UIButton) {
        self.dismiss(animated: false)
    }
    
    @IBAction func didSelctStatus(_ sender: UIButton) {
        if sender.isSelected { return }
        sender.isSelected = !sender.isSelected
        if sender == yesButton {
            noButton.isSelected = false
            model.isRepeat = true
        }
        if sender == noButton {
            yesButton.isSelected = false
            model.isRepeat = false
        }
    }
    
    @IBAction func didSubmit(_ sender: UIButton) {
        if let text = taskName.text, !text.isEmpty {
            model.taskName = text
        }else {
            self.view.makeToast("请输入名称", position: .center)
        }
        if let text = number.text, !text.isEmpty {
            model.number = Int(text) ?? 0
            for _ in 1...model.number {
                let item = UTTaskCounterFinishModel()
                model.programmeList.append(item)
            }
        }else {
            self.view.makeToast("请输入完成次数", position: .center)
        }
        if let text = note.text, !text.isEmpty {
            model.note = text
        }
        model.no = data.datas.count
        data.datas.append(model)
        UTTaskCounterHelper.dc_saveTaskCounterInfo(taskCounter: data)
        UIApplication.shared.keyWindow?.makeToast("添加成功", position: .center)
        self.dismiss(animated: false)
        if let handler = reloadData {
            handler()
        }
        
    }
}
